package edu.gatech.asthma.database;

import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * Database adapter
 * Use adapter to communicate with the database
 */
public class DBAdapter {

	private SQLiteDatabase database;
	private DBHelper myHelper;

	public DBAdapter(Context context) {
		myHelper = new DBHelper(context);
	}

	/**
	 * Check if the database is available
	 * @return true if available
	 * @throws SQLException
	 */
	public DBAdapter open() throws SQLException {
		try {
			database = myHelper.getWritableDatabase();
		} catch (SQLException e) {
			throw e;
		}
		return this;
	}

	/**
	 * Close the database
	 */
	public void close() {
		myHelper.close();
	}

	/**
	 * Add a profile into the database
	 * @param name 
	 * @param gender
	 * @param birthday
	 * @param weight 
	 * @param weightUnit pounds or kilograms
	 * @param height
	 * @param heightUnit centimeters or feet/inches
	 * @param ethnicity 
	 * @param bg_color customized background color
	 * @param tint_color tint color for the pic
	 * @param accent_color accent color for the pic
	 * @param pic customized picture for the profile
	 * @return identifier of newly created profile
	 */
	public int addProfile(String name, int gender, String birthday, int weight, int weightUnit, int height, int heightUnit, int ethnicity, int bg_color, int tint_color, int accent_color, int pic){
		int count=0;
		try{
			String sql = "select identifier from user_profile;";
			Cursor myCur = database.rawQuery(sql, null);
			if(myCur != null) {
				count=myCur.getCount();
			}
			myCur.close();
		} catch (SQLException e) {
			throw e;
		}
		try{
			String sql = "insert into user_profile values ('"
					+count+"','"+name+"','"+gender+"','"+birthday+"','"+weight+"','"+weightUnit+"','"+height+"','"+heightUnit+"','"+ethnicity+"','"+bg_color+"','"+tint_color+"','"+accent_color+"','"+pic+"',0);";
			database.execSQL(sql);
		} catch (SQLException e) {
			Log.d("UI","unable to add profile");
			throw e;
		}
		return count; //identifier of newly created profile
	}

	/**
	 * Update the profile
	 * @param identifier profile identifier
	 * @param name
	 * @param gender
	 * @param birthday
	 * @param weight
	 * @param weightUnit
	 * @param height
	 * @param heightUnit
	 * @param ethnicity
	 * @param bg_color
	 * @param tint_color
	 * @param accent_color
	 * @param pic
	 * @param best personal best for the subjunctive tests
	 */
	public void updateProfile(int identifier, String name, int gender, String birthday, int weight, int weightUnit, int height, int heightUnit, int ethnicity, int bg_color, int tint_color, int accent_color, int pic, float best){
		deleteProfile(identifier);
		try{
			String sql = "insert into user_profile values ('"
					+identifier+"','"+name+"','"+gender+"','"+birthday+"','"+weight+"','"+weightUnit+"','"+height+"','"+heightUnit+"','"+ethnicity+"','"+bg_color+"','"+tint_color+"','"+accent_color+"','"+pic+"','"+best+"');";
			database.execSQL(sql);
		} catch (SQLException e) {
			throw e;
		}
	}

	/**
	 * Get certain profile based on the identifier
	 * @param identifier profile identifier
	 * @return a profile value object containing all the information
	 */
	public ProfileVO getProfile(int identifier){
		try{
			ProfileVO profile = new ProfileVO();
			String sql = "select * from user_profile where identifier='"+identifier+"';";
			Cursor myCur = database.rawQuery(sql, null);
			if(myCur != null) {
				myCur.moveToFirst();
				profile.setIdentifier(myCur.getInt(0));
				profile.setName(myCur.getString(1));
				profile.setGender(myCur.getInt(2));
				profile.setBirthday(myCur.getString(3));
				profile.setWeight(myCur.getInt(4));
				profile.setWeight_unit(myCur.getInt(5));
				profile.setHeight(myCur.getInt(6));
				profile.setHeight_unit(myCur.getInt(7));
				profile.setEthnicity(myCur.getInt(8));
				profile.setBgColor(myCur.getInt(9));
				profile.setTintColor(myCur.getInt(10));
				profile.setAccentColor(myCur.getInt(11));
				profile.setPic(myCur.getInt(12));
				profile.setBest(myCur.getFloat(13));
			}
			myCur.close();
			return profile;
		} catch (SQLException e) {
			throw e;
		}
	}

	/**
	 * Remove profile from database based on the identifier
	 * @param identifier
	 */
	public void deleteProfile(int identifier){
		try{
			String sql = "delete from user_profile where identifier='"+identifier+"';";
			database.execSQL(sql);
		} catch (SQLException e) {
			throw e;
		}
	}

	/**
	 * Get the total number of profiles in the database
	 * @return total number of profiles
	 */
	public int getNumProfiles() {
		int count=0;
		try{
			String sql = "select identifier from user_profile;";
			Cursor myCur = database.rawQuery(sql, null);
			if(myCur != null) {
				count=myCur.getCount();
			}
			myCur.close();
		} catch (SQLException e) {
			throw e;
		}
		Log.d("UI","Number of profiles: "+count);
		return count;
	}

	/**
	 * Add a symptom record to the databse
	 * @param identifier the profile related to the record
	 * @param time time stamp for the symptom
	 * @param symptoms a string of 0's and 1's indicating which symptom the patient has, 1 means having the symptom
	 */
	public void addSymptomRecord(int identifier, String time, String symptoms) {
		try{
			String sql = "insert into symptom_record (identifier, time, symptoms) values ('" + identifier+"','"+time+"','"+symptoms+"');";
			database.execSQL(sql);
		} catch (SQLException e) {
			Log.d("DATABASE", "Unable to add symptom record");
			throw e;
		}
	}

	/**
	 * Get all symptom records based on the identifier
	 * @param identifier
	 * @return a list of symptom record value objects
	 */
	public ArrayList<SymptomRecordVO> getSymptomRecords(int identifier) {
		ArrayList<SymptomRecordVO> list = new ArrayList<SymptomRecordVO>();
		try {
			String sql = "select * from symptom_record where identifier='"+identifier+"';";
			Cursor myCur = database.rawQuery(sql, null);
			if(myCur != null) {
				myCur.moveToFirst();
				while(!myCur.isAfterLast()) {
					SymptomRecordVO record = new SymptomRecordVO();
					record.setId(myCur.getInt(0));
					record.setIdentifier(myCur.getInt(1));
					record.setDate(myCur.getString(2));
					record.setSymptoms(myCur.getString(3));
					list.add(record);
					myCur.moveToNext();
				}
				myCur.close();
			}
			return list;
		} catch (SQLException e) {
			throw e;
		}
	}

	/**
	 * Get certain symptom record based on a unique id
	 * @param id record id
	 * @return symptom record value object
	 */
	public SymptomRecordVO getSymptomRecordByID(int id) {
		SymptomRecordVO record = new SymptomRecordVO();
		try {
			String sql = "select * from symptom_record where _id ='"+id+"';";
			Cursor myCur = database.rawQuery(sql, null);
			if(myCur != null) {
				myCur.moveToFirst();
				record.setId(myCur.getInt(0));
				record.setIdentifier(myCur.getInt(1));
				record.setDate(myCur.getString(2));
				record.setSymptoms(myCur.getString(3));
			}
			myCur.close();
			return record;
		} catch (SQLException e) {
			throw e;
		}
	}

	/**
	 * Check if the patient has any symptom records
	 * @param identifier the identifier of the patient
	 * @return true if there are records, false otherwise
	 */
	public boolean hasSymptomRecords(int identifier) {
		int count = 0;
		try{
			String sql = "select * from symptom_record where identifier='"+identifier+"';";
			Cursor myCur = database.rawQuery(sql, null);
			if(myCur != null) {
				count=myCur.getCount();
			}
			myCur.close();
			if(count == 0) {
				return false;
			} else {
				return true;
			}
		} catch (SQLException e) {
			throw e;
		}
	}
	
	/**
	 * Save the subjunctive test results to the database
	 * @param identifier
	 * @param resistance test result
	 * @param reactance test result
	 * @param date the date that the test happens
	 */
	public void addTestResult(int identifier, float resistance, float reactance, String date) {
		try{
			String sql = "insert into test_result values ('" + identifier+"','"+resistance+"','"+reactance+"','"+date+"');";
			database.execSQL(sql);
		} catch (SQLException e) {
			Log.d("DATABASE", "Unable to add symptom record");
			throw e;
		}
	}

	/**
	 * Add a emergency contact
	 * @param name contact's name
	 * @param number contact's number
	 */
	public void addEmergencyContact(String name, String number) {
		try{
			String sql = "insert into emergency_contact values ('" + name+"','"+number+"');";
			database.execSQL(sql);
		} catch (SQLException e) {
			Log.d("DATABASE", "Unable to add symptom record");
			throw e;
		}
	}

	/**
	 * Get all emergency contacts
	 * @return a list of all the emergency contacts
	 */
	public ArrayList<ContactVO> getContactList() {
		ArrayList<ContactVO> list = new ArrayList<ContactVO>();
		try {
			String sql = "select * from emergency_contact;";
			Cursor myCur = database.rawQuery(sql, null);
			if(myCur != null) {
				myCur.moveToFirst();
				while(!myCur.isAfterLast()) {
					ContactVO contact = new ContactVO();
					contact.setName(myCur.getString(0));
					contact.setNumber(myCur.getString(1));
					list.add(contact);
					myCur.moveToNext();
				}
				myCur.close();
			}
			return list;
		} catch (SQLException e) {
			throw e;
		}
	}

	/**
	 * Check if there are any emergency contacts
	 * @return true if at least one contact exists, false otherwise
	 */
	public boolean hasContacts() {
		int count = 0;
		try{
			String sql = "select * from emergency_contact;";
			Cursor myCur = database.rawQuery(sql, null);
			if(myCur != null) {
				count=myCur.getCount();
			}
			myCur.close();
			if(count == 0) {
				return false;
			} else {
				return true;
			}
		} catch (SQLException e) {
			throw e;
		}
	}

	/**
	 * Get the contact's number based on the name
	 * @param name contact's name
	 * @return contact's phone number
	 */
	public String getNumberByContactName(String name) {
		String number = "";
		try {
			String sql = "select number from emergency_contact where name ='"+name+"';";
			Cursor myCur = database.rawQuery(sql, null);
			if(myCur != null) {
				myCur.moveToFirst();
				number = myCur.getString(0);
			}
			myCur.close();
			return number;
		} catch (SQLException e) {
			throw e;
		}
	}
}

